package com.foreverwin.jzymes.eap.Listener;

import com.alibaba.fastjson.JSONObject;
import com.foreverwin.jzymes.common.domain.CarrierScanLog;
import com.foreverwin.jzymes.common.util.CarrierUtil;
import com.foreverwin.jzymes.framework.annotation.MessageLog;
import com.foreverwin.jzymes.framework.event.AppEvent;
import com.foreverwin.jzymes.framework.event.AppEventPublisher;
import com.foreverwin.jzymes.framework.util.ObjectMapperUtil;
import com.foreverwin.jzymes.production.clamp.service.IClampAdviceService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
public class ClampListener {
    private Logger logger = LoggerFactory.getLogger( ClampListener.class );

    @Autowired
    IClampAdviceService clampAdviceService;
    @Autowired
    AppEventPublisher appEventPublisher;

    @JmsListener( destination = "MES_CLAMP_INFRA" )
    @MessageLog
    public void clampCarrierFromQueue( String carrierScanLogJson ) throws IOException {
        logger.info( "接收到装夹信息: " + carrierScanLogJson );
        try{
            CarrierScanLog carrierScanLog = ObjectMapperUtil.readValueForUnderscore( carrierScanLogJson, CarrierScanLog.class );
            carrierScanLog.setCarrier( CarrierUtil.buildCarrier( carrierScanLog.getSite(), carrierScanLog.getCarrier() ) );
            clampAdviceService.clampCarrier( carrierScanLog );

            /**发布事件*/
            if( "Y".equals( carrierScanLog.getPass() ) ){
                JSONObject eventData = new JSONObject();
                eventData.put( "SITE", carrierScanLog.getSite() );
                eventData.put( "CARRIER", carrierScanLog.getCarrier() );
                eventData.put( "RESRCE", carrierScanLog.getResrce() );
                AppEvent<JSONObject> appEvent = new AppEvent<>( this );
                appEvent.setName( "CARRIER_CHECK_OUT_EVENT" );
                appEvent.setData( eventData );
                appEventPublisher.publishEvent( appEvent );
            }

            logger.info( "装夹信息处理完成: " + carrierScanLogJson );
        }catch ( Exception e ){
            logger.error( "装夹信息处理失败: " + e.getMessage() + "，装夹信息: " + carrierScanLogJson );
            throw e;
        }
    }
}
